<template>
<el-container>
  <el-aside width="200px" style="background-color: rgb(238, 241, 246)">
    <el-tree
      style="height: 100%;border-right: 1px solid #bbb;"
      :data="treedata"
      :props='defaultProps'
      :expand-on-click-node="false"
      @node-click="handleNodeClick"
      node-key="id"
      accordion
      default-expand-all
      highlight-current
      check-on-click-node
    ></el-tree>
  </el-aside>

  <el-container>
    <el-header>
      <el-button-group>
        <el-button type="primary" icon="el-icon-add" @click="addView">新增</el-button>
      </el-button-group>
    </el-header>

    <el-main>
      <el-table :data="tableData" max-height="740" highlight-current-row @current-change="handleCurrentChange">
        <el-table-column
          type="index"
          width="50">
        </el-table-column>
        <el-table-column prop="number" label="视图编号" width="140">
        </el-table-column>
        <el-table-column prop="name" label="视图名称" width="250">
        </el-table-column>
        <!-- <el-table-column prop="tableName" label="关联表名" width="120">
        </el-table-column>
        <el-table-column prop="enabled" label="是否启用" width="120">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.enabled"
              :active-value= 1
              :inactive-value= 0
              active-color="#409EFF"
              inactive-color="#ff4949"
              disabled>
            </el-switch>
          </template>
        </el-table-column> -->
        <el-table-column prop="createDate" label="创建时间">
        </el-table-column>
        <el-table-column align="right" fixed="right" width="250">
          <template slot="header">
            <el-input
              v-model="search"
              size="mini"
              placeholder="输入关键字搜索"/>
          </template>
          <template slot-scope="scope">
            <el-button
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)"></el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope.$index, scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-dialog :title="title" :destroy-on-close="true" :close-on-click-modal="false" :visible.sync="dialogFormVisible" :before-close="handleCloseBindDialogForm" width="75%" top="12vh">
      <div  style="height:63vh">
        <el-steps :active="stepsActive" finish-status="success">
          <el-step title="基础配置"></el-step>
          <el-step title="查看JSON"></el-step>
          <el-step title="效果预览"></el-step>
        </el-steps>

        <el-container :style="{'display':stepsActive==1?'block':'none'}" >
          <!-- <df-element-form :formConfig="formConfig[0]" :value="formValue" ref="customForm"></df-element-form> -->
          <el-divider content-position="left">视图配置
            <el-button
              size="mini"
              @click="addWholeConfigArrayRow()">新增</el-button>
          </el-divider>
          <el-table
            max-height="500"
            :data="wholeConfigArray"
            style="width: 100%">
            <el-table-column
              prop="title"
              label="标题">
            </el-table-column>
            <el-table-column
              prop="tableName"
              label="关联表名">
            </el-table-column>
            <!-- <el-table-column
              prop="inline"
              label="行内表单模式">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.inline"
                  disabled>
                </el-switch>
              </template>
            </el-table-column> -->
            <el-table-column
              prop="labelPosition"
              label="标签对齐方式">
              <template slot-scope="scope">
                <span v-if="scope.row.labelPosition == 'left'">左对齐</span>
                <span v-else-if="scope.row.labelPosition == 'right'">右对齐</span>
                <span v-else-if="scope.row.labelPosition == 'top'">顶部对齐</span>
                <span v-else></span>
              </template>
            </el-table-column>
            <el-table-column
              prop="labelWidth"
              label="标签宽度">
            </el-table-column>
            <el-table-column
              prop="size"
              label="尺寸">
              <template slot-scope="scope">
                <el-select v-model="scope.row.size"  placeholder="请选择" disabled>
                  <el-option label="默认" value=""></el-option>
                  <el-option label="中" value="medium"></el-option>
                  <el-option label="小" value="small"></el-option>
                  <el-option label="迷你" value="mini"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="disabled"
              label="禁用">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.disabled">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="180">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="editWholeConfigArrayRow(scope.$index, scope.row)">编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click.native.prevent="deleteWholeConfigArrayRow(scope.$index, wholeConfigArray)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-dialog
            :title="wholeConfigDialogTitle"
            width="70%"
            top="14vh"
            :destroy-on-close="true"
            :close-on-click-modal="false"
            :visible.sync="wholeConfigVisible"
            :before-close="handleCloseBindWholeConfigDialog"
            append-to-body>
            <el-container style="height:58vh; border: 1px solid #eee">
              <el-aside width="400px" style="background-color: rgb(238, 241, 246);height:100%;display: inline-block;padding:0 10px">
                <el-tabs v-model="fieldConfigTabName" @tab-click="handleFieldConfigTabClick">
                  <el-tab-pane label="添加元素" name="first">
                    <div style="display: inline-block;margin: 10px;" v-for="ele in eles" :key="ele.type">
                      <div v-if="!ele.child || ele.child.length <= 0" @click="eleSelect({type:ele.type,subtype:ele.subtype})">
                        <span class="demonstration">{{ ele.name }}
                          <el-image
                          :src="ele.imgUrl"
                          :ele="ele"></el-image>
                        </span>
                      </div>
                      <el-dropdown trigger="click" @command="eleSelect" v-if="ele.child && ele.child.length > 0">
                        <span class="el-dropdown-link demonstration">
                          {{ ele.name }}
                          <el-image
                            :src="ele.imgUrl"
                            :ele="ele"></el-image>
                        </span>
                        <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item v-for="eleItem in ele.child" :key="eleItem.type" :command="{type:eleItem.type,subtype:eleItem.subtype}"> {{ eleItem.name }}</el-dropdown-item>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </div>
                  </el-tab-pane>
                  <el-tab-pane label="元素配置" name="second">
                    <eles-options
                      :eleConfigData="eleConfigData"
                      v-if="wholeConfigData['formItemList'][selectFormItemIndex] && wholeConfigData['formItemList'][selectFormItemIndex]['type'] && wholeConfigData['formItemList'][selectFormItemIndex]['type']!='' && (wholeConfigData['formItemList'][selectFormItemIndex].type=='select'||wholeConfigData['formItemList'][selectFormItemIndex].type=='checkbox'||wholeConfigData['formItemList'][selectFormItemIndex].type=='radio')"
                    ></eles-options>
                    <eles-cascader
                      :eleConfigData="eleConfigData"
                      v-else-if="wholeConfigData['formItemList'][selectFormItemIndex] && wholeConfigData['formItemList'][selectFormItemIndex]['type'] && wholeConfigData['formItemList'][selectFormItemIndex]['type']!='' && (wholeConfigData['formItemList'][selectFormItemIndex].type=='cascader')"
                    ></eles-cascader>
                    <eles-upload
                      :eleConfigData="eleConfigData"
                      v-else-if="wholeConfigData['formItemList'][selectFormItemIndex] && wholeConfigData['formItemList'][selectFormItemIndex]['type'] && wholeConfigData['formItemList'][selectFormItemIndex]['type']!='' && (wholeConfigData['formItemList'][selectFormItemIndex].type=='upload')"
                    ></eles-upload>
                    <eles-switch
                      :eleConfigData="eleConfigData"
                      v-else-if="wholeConfigData['formItemList'][selectFormItemIndex] && wholeConfigData['formItemList'][selectFormItemIndex]['type'] && wholeConfigData['formItemList'][selectFormItemIndex]['type']!='' && (wholeConfigData['formItemList'][selectFormItemIndex].type=='switch')"
                    ></eles-switch>
                    <eles-input :eleConfigData="eleConfigData" v-else></eles-input>
                    <el-card>
                      <pre>{{wholeConfigData['formItemList'][selectFormItemIndex]}}</pre>
                    </el-card>
                  </el-tab-pane>
                  <el-tab-pane label="全局配置" name="third">
                    <el-form ref="wholeConfigData" :model="wholeConfigData" label-width="80px" size="mini">
                      <el-form-item label="标题">
                        <el-input v-model="wholeConfigData.title"></el-input>
                      </el-form-item>
                      <el-form-item label="关联表名">
                        <el-input v-model="wholeConfigData.tableName"></el-input>
                      </el-form-item>
                      <!-- <el-form-item label="行内表单模式">
                        <el-switch v-model="wholeConfigData.inline"></el-switch>
                      </el-form-item> -->
                      <el-form-item label="标签对齐方式">
                        <el-radio-group v-model="wholeConfigData.labelPosition" size="small">
                          <el-radio-button label="left">左对齐</el-radio-button>
                          <el-radio-button label="right">右对齐</el-radio-button>
                          <el-radio-button label="top">顶部对齐</el-radio-button>
                        </el-radio-group>
                      </el-form-item>
                      <el-form-item label="标签宽度">
                        <el-input v-model="wholeConfigData.labelWidth"></el-input>
                      </el-form-item>
                      <el-form-item label="尺寸">
                        <el-select v-model="wholeConfigData.size" placeholder="请选择">
                          <el-option label="默认" value=""></el-option>
                          <el-option label="中" value="medium"></el-option>
                          <el-option label="小" value="small"></el-option>
                          <el-option label="迷你" value="mini"></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="验证图标">
                        <el-switch v-model="wholeConfigData.statusIcon"></el-switch>
                      </el-form-item>
                      <el-form-item label="禁用">
                        <el-switch v-model="wholeConfigData.disabled"></el-switch>
                      </el-form-item>
                    </el-form>
                  </el-tab-pane>
                  <el-tab-pane label="查看JSON" name="fourth">
                    <el-card class="box-card" style="height: 57vh;">
                      <pre>{{wholeConfigData}}</pre>
                    </el-card>
                  </el-tab-pane>
                </el-tabs>
              </el-aside>
              <el-main class="lookForm-main" style="height:100%;width:calc(100% - 400px);display: inline-block;">
                <fake-form :formConfig="wholeConfigData" :selectFormItemIndex="selectFormItemIndex" ref="lookForm" @handelSelectFormItem="handelSelectFormItem" @handelDeleteFormItem="handelDeleteFormItem"></fake-form>
              </el-main>
            </el-container>
            <el-row slot="footer" class="dialog-footer" style="text-align: center;">
              <el-button type="primary" @click="wholeConfigSave">保存</el-button>
              <el-button @click="wholeConfigVisible = false;">取消</el-button>
            </el-row>
          </el-dialog>
        </el-container>
        <el-container :style="{'display':stepsActive==2?'block':'none'}" style="height: 100%;">
          <el-card class="box-card" style="height: 64vh;background: #eef1f6;">
            <pre>{{wholeConfigArray}}</pre>
          </el-card>
        </el-container>
        <div :style="{'display':stepsActive==3?'block':'none'}" style="height: 100%;overflow: auto;">
          <df-element-form
            v-for="(item,i) in wholeConfigArray"
            :key="i"
            :formConfig="item"
            ref="lookAllForm"
          ></df-element-form>
        </div>
      </div>
      <el-row slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="prev" :style="{'display':stepsActive!=1?'inline-block':'none'}">上一步</el-button>
        <el-button @click="next" :style="{'display':stepsActive!=3?'inline-block':'none'}">下一步</el-button>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="dialogFormVisible = false;stepsActive=1">取消</el-button>
      </el-row>
    </el-dialog>
  </el-container>
</el-container>
</template>

<style scoped>
  .el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
  }

  .el-aside {
    color: #333;
  }
</style>

<script>
  import { getEles } from '@/const/views/system/viewConfig'
  import { isNull, deepClone } from '@/util/util'
  import FakeForm from './viewForm/fake-form'
  import elesCascader from './eleForm/eles-cascader'
  import elesInput from './eleForm/eles-input'
  import elesOptions from './eleForm/eles-options'
  import elesUpload from './eleForm/eles-upload'
  // import elesSwitch from './eleForm/eles-switch'
  export default {
    components: { FakeForm, elesCascader, elesInput, elesOptions, elesUpload },
    data() {
      return {
        tableData: [],
        search: '',
        treedata: [],
        defaultProps: {
          children: 'sub',
          label: 'title'
        },
        dialogFormVisible: false,
        title: '',
        currentTreeNode: null,
        currentRow: null,
        pathUrl: '',
        stepsActive: 1,
        formValue: {},
        fieldConfigTabName: 'first',
        eles: Array,
        eleConfigData: {
          "label": "",
          "placeholder": "",
          "rules": [{
            required: true,
            message: '必填项',
            trigger: 'change',
          }],
          "key": "",
          "value": "",
          "disabled": false,
          "hide": false,
          "spannum": 6,
          "options": [],
          "optionsUrl": "",
          "checkStrictly": false,
          "multiple": false,
          "uploadUrl": "",
          "dataType": "object",
          "limit": 0,
          "fileType": [],
          "size": '',
          'activeValue': true,
          'inactiveValue': false
        },
        wholeConfigData: {
          "title": "",
          "tableName": "",
          "disabled": false,
          // "inline": false,
          "labelPosition": "right",
          "labelWidth": "80px",
          "size": "small",
          "statusIcon": true,
          "formItemList": []
        },
        eleconfigJson: {
          "type": "",
          "label": "",
          "disabled": false,
          "hide": false,
          "value": "",
          "placeholder": "",
          "rules": [{
            required: true,
            message: '必填项',
            trigger: 'change',
          }],
          "key": "",
          "subtype": "",
          "spannum": 6,
          "options": [],
          "optionsUrl": "",
          "checkStrictly": false,
          "multiple": false,
          "uploadUrl": "",
          "dataType": "object",
          "limit": 0,
          "fileType": [],
          "size": '',
          'activeValue': true,
          'inactiveValue': false
        },
        selectFormItemIndex: 0,
        wholeConfigArray: [],
        wholeConfigVisible: false,
        wholeConfigDialogTitle: '',
        editWholeConfigIndex: 0
      }
    },
    created() {
      this.getTreeData();
      // this.getViewDate();
      this.getEles();
    },
    methods: {
      //获取树数据
      getTreeData() {
        let _this = this
        _this.axios.post(_this.GLOBAL.proxyUrl + 'saas/sys.Systems/getAuthMenus/version/v1') 
        .then((res)=>{
          console.log(res)
          _this.treedata = res.data.data.menus
        })
        .catch((err)=>{
          _this.treedata = []
          console.log('调用失败',err)
        })
      },
      //树选中节点点击
      handleNodeClick(data) {
        this.currentTreeNode = data
        this.pathUrl = this.currentTreeNode.component
        try {
          this.wholeConfigArray = require(`@/const/${this.pathUrl}.js`).getFormConfigData()
          this.tableData = [{
            'id': 1,
            'menuId': data.id,
            'number': '0001',
            'name': data.title + '配置',
            'enabled': 1,
            'createDate': ''
          }]
        } catch (error) {
          this.wholeConfigArray = []
          this.tableData = []
        }
      },
      //表格选中行
      handleCurrentChange(val) {
        this.currentRow = val
      },
      //表格行编辑
      handleEdit(index, row) {
        if(!isNull(this.currentTreeNode) && this.currentTreeNode['component'] && this.currentTreeNode.component != ""){
           console.log(index, row)
          this.formValue = row
          this.title="编辑视图"
          this.dialogFormVisible = true
          this.dialogDataClear()
        }
      },
      //表格行删除
      handleDelete(index, row) {
        console.log(index, row)
      },
      //新增按钮
      addView(){
        if(!isNull(this.currentTreeNode)){
          this.formValue = {}
          this.title="新增视图"
          this.dialogFormVisible = true
          this.dialogDataClear()
        }
      },
      // 绑定弹窗子组件的关闭
      handleCloseBindDialogForm() {
        this.title=""
        this.dialogFormVisible = false
      },
      // 上一步
      prev() {
        this.stepsActive--
      },
      // 下一步
      next() {
        this.stepsActive++
      },
      // 弹出框中data值重置
      dialogDataClear() {
        this.stepsActive=1
        this.$data.formValue = Object.assign({}, this.$options.data().formValue)
        this.fieldConfigTabName='first'
        this.$data.eleConfigData = Object.assign({}, this.$options.data().eleConfigData)
        this.$data.wholeConfigData = Object.assign({}, this.$options.data().wholeConfigData)  
        // this.$data.wholeConfigArray = []
      },
      // 表单配置保存
      save() {
        this.$refs.customForm.formData
        this.stepsActive = 1
      },
      // 表单元素配置界面页签
      handleFieldConfigTabClick(tab, event) {
        console.log(tab, event);
        this.fieldConfigTabName = tab.name;
      },
      //获取元素组件
      getEles() {
        this.eles = getEles()
      },
      //点击选择元素、下拉选择元素
      eleSelect(type) {  
        //当前元素类型
        this.$data.eleConfigData = Object.assign({}, this.$options.data().eleConfigData)
        this.fieldConfigTabName = "second"
        this.eleconfigJson = Object.assign({}, this.$options.data().eleconfigJson)

        let eleconfigObj = Object.assign({}, deepClone(this.eleconfigJson))
        this.$set(eleconfigObj, 'type', type.type)
        this.$set(eleconfigObj, 'subtype', type.subtype)
        let foreItemLenth = this.wholeConfigData.formItemList.length
        this.$set(this.wholeConfigData.formItemList, foreItemLenth, eleconfigObj)
        this.$set(this, 'selectFormItemIndex', foreItemLenth)
        console.log(this.$data.wholeConfigData)
      },
      //选择元素
      handelSelectFormItem(index) {
        this.selectFormItemIndex = index
        for (let key in this.eleConfigData) {
          if(this.wholeConfigData.formItemList[this.selectFormItemIndex].hasOwnProperty(key)){
            this.$set(this.eleConfigData, key, this.wholeConfigData.formItemList[this.selectFormItemIndex][key])
          }
        }
      },
      //删除元素
      handelDeleteFormItem(index) {
        this.wholeConfigData.formItemList.splice(index, 1);
      },
      // 绑定弹窗子组件的关闭
      handleCloseBindWholeConfigDialog() {
        this.wholeConfigVisible = false
        this.wholeConfigDialogTitle = ""
      },
      //关闭视图配置时,清空相关data
      clearWholeConfigArray(){
        this.fieldConfigTabName = "first";
        if(this.wholeConfigData.formItemList.length > 0){
          for (let key in this.eleConfigData) {
            if(this.wholeConfigData.formItemList[0].hasOwnProperty(key)){
              this.$set(this.eleConfigData, key, this.wholeConfigData.formItemList[0][key])
            }
          }
        }else{
          this.$data.eleConfigData = Object.assign({}, this.$options.data().eleConfigData)
        }        
        this.eleconfigJson = Object.assign({}, this.$options.data().eleconfigJson)
        this.selectFormItemIndex = 0
      },
      //新增视图配置行
      addWholeConfigArrayRow(){
        this.wholeConfigVisible = true
        this.wholeConfigDialogTitle = "新增"
        this.editWholeConfigIndex = this.wholeConfigArray.length
        this.$data.wholeConfigData = Object.assign({}, this.$options.data().wholeConfigData)
        this.clearWholeConfigArray()
      },
      //编辑视图配置行
      editWholeConfigArrayRow(index, row){
        console.log(index, row)
        this.editWholeConfigIndex = index
        this.wholeConfigVisible = true
        this.wholeConfigDialogTitle = "编辑"
        this.wholeConfigData = Object.assign({}, row)
        this.clearWholeConfigArray()
      },
      //视图配置保存
      wholeConfigSave(){
        let wholeConfigDataObj = Object.assign({}, deepClone(this.wholeConfigData))
        this.$set(this.wholeConfigArray, this.editWholeConfigIndex, wholeConfigDataObj)
        this.wholeConfigVisible = false
      },
      //删除视图配置行
      deleteWholeConfigArrayRow(index, rows){
        rows.splice(index, 1);
      },
    },
    watch: {
      eleConfigDataNew: {
        handler(val,oldval) {
          for (let key in val) {
            if(val[key] != oldval[key]){
              this.$set(this.wholeConfigData.formItemList[this.selectFormItemIndex], key, val[key])
            }
          }
          // this.$set(this.wholeConfigData.formItemList, this.selectFormItemIndex, val)
        },
        deep: true
      },
    },
    computed: {
      eleConfigDataNew() {
        return JSON.parse(JSON.stringify(this.eleConfigData))
      }
    }
  };
</script>

<style lang="scss">
.demonstration {
  width: 60px;
  height:60px;
  display: inline-block;
  text-align: center;
  color: #409EFF;
  background: #d9ecff;
  padding: 2px;
  .el-image {
    width: 30px;
    height: 30px;
    display: block;
    align-items: center;
    margin: 5px auto;
  }
}
.lookForm-main {
  padding: 10px !important;
}
// .ele-json-card {
//   height: 23vh;
// }
// .el-tabs__content {
//   height: 58vh;
//   overflow: auto;
// }
.el-card.box-card {
  overflow: auto;
}
.eleConfigForm {
  .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
    margin-bottom: 5px;
  }
}
.option-config {
  border: 1px dashed #409EFF;
  padding-top: 5px;
  margin-bottom: 5px;
  .el-input-group__prepend {
   padding: 0 8px;
  }
  .del-option {
    position: absolute;
    top: 1px;
    right: 2px;
    color: red;
    cursor: pointer;
  }
  .el-switch {
    padding: 10px 0 5px 3px;
  }
}
</style>